package base;

import java.util.HashMap;

public class TestLRUCache {

    private static class DLinkedNode {
        int key;
        int value;
        DLinkedNode prev;
        DLinkedNode next;

        public DLinkedNode() {
        }

        public DLinkedNode(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    private HashMap<Integer, DLinkedNode> cache = new HashMap<>();
    private DLinkedNode head;
    private DLinkedNode tail;
    private int capacity;
    private int size;

    public TestLRUCache(int capacity) {
        this.capacity = capacity;
        head = new DLinkedNode();
        tail = new DLinkedNode();
        head.next = tail;
        tail.prev = head;
    }

    public void put(int key, int value) {
        DLinkedNode node = cache.get(key);
        // 缓存中不存在
        if (node == null) {
            node = new DLinkedNode(key, value);
            addToHead(node);
            size++;
            cache.put(node.key, node);
            if (size > capacity) {
                DLinkedNode lastNode = removeLast();
                cache.remove(lastNode.key);
            }
        } else {
            node.value = value;
            moveToHead(node);
        }
        print();
    }

    public int get(int key) {
        DLinkedNode node = cache.get(key);
        if (null == node) {
            return -1;
        }
        moveToHead(node);
        print();
        return node.value;
    }

    private void remove(DLinkedNode node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private DLinkedNode removeLast() {
        DLinkedNode lastNode = tail.prev;
        remove(lastNode);
        return lastNode;
    }

    private void addToHead(DLinkedNode node) {
        node.next = head.next;
        head.next.prev = node;
        node.prev = head;
        head.next = node;
    }

    private void moveToHead(DLinkedNode node) {
        remove(node);
        addToHead(node);
    }

    private void print() {
        StringBuilder sb = new StringBuilder();
        DLinkedNode node = head.next;
        while (node != tail) {
            sb.append(node.key).append("=").append(node.value).append(", ");
            node = node.next;
        }
        System.out.println(sb);
    }

    public static void main(String[] args) {
        TestLRUCache cache = new TestLRUCache(3);
        cache.put(1, 1);
        cache.put(2, 2);
        cache.put(3, 3);
        cache.get(2);
        cache.get(3);
        cache.put(4, 4);
        cache.get(2);
        cache.put(5, 5);
    }
}
